"""Lead AI summary repository implementation (Synchronous)."""

from __future__ import annotations

from sqlalchemy.orm import Session

from ..models.lead_ai_summary import LeadAISummary
from .base import Repository
from ..schemas.lead_ai_summary import LeadAISummaryCreate, LeadAISummaryUpdate


class LeadAISummaryRepository(Repository[LeadAISummary, LeadAISummaryCreate, LeadAISummaryUpdate]):
    """Repository for LeadAISummary operations (Synchronous)."""

    def __init__(self, session: Session) -> None:
        super().__init__(LeadAISummary, session)

    def get_by_lead(self, lead_id: int) -> list[LeadAISummary]:
        """Get all AI summaries for a specific lead."""
        return (
            self.session.query(LeadAISummary)
            .filter(LeadAISummary.lead_id == lead_id)
            .order_by(LeadAISummary.created_at.desc())
            .all()
        )

    def get_latest_by_lead(self, lead_id: int) -> LeadAISummary | None:
        """Get the most recent AI summary for a lead."""
        return (
            self.session.query(LeadAISummary)
            .filter(LeadAISummary.lead_id == lead_id)
            .order_by(LeadAISummary.created_at.desc())
            .first()
        )

    def get_unreviewed(self, limit: int = 50) -> list[LeadAISummary]:
        """Get unreviewed AI summaries."""
        return (
            self.session.query(LeadAISummary)
            .filter(LeadAISummary.reviewed == False)  # noqa: E712
            .order_by(LeadAISummary.created_at.desc())
            .limit(limit)
            .all()
        )

    def mark_reviewed(self, summary_id: int, reviewer_id: int) -> LeadAISummary | None:
        """Mark an AI summary as reviewed."""
        summary = self.get(summary_id)
        if summary is None:
            return None

        summary.reviewed = True
        summary.reviewer_id = reviewer_id

        self.session.commit()
        self.session.refresh(summary)
        return summary
